import SockJS from 'sockjs-client'
import { Stomp } from '@stomp/stompjs'

let stompClient = null
let subscriptions = {}

export const connectWebSocket = (onConnected) => {
  try {
    const socket = new SockJS('http://localhost:8080/ws')
    stompClient = Stomp.over(socket)
    stompClient.connect({}, () => {
      console.log('WebSocket连接成功')
      if (onConnected) {
        onConnected()
      }
    }, (error) => {
      console.error('WebSocket连接失败:', error)
      setTimeout(() => {
        connectWebSocket(onConnected)
      }, 5000)
    })
  } catch (error) {
    console.error('WebSocket初始化失败:', error)
  }
}

export const disconnectWebSocket = () => {
  if (stompClient) {
    stompClient.disconnect()
  }
}

export const subscribeToTopic = (topic, callback) => {
  if (!stompClient) {
    console.error('WebSocket未连接')
    return
  }
  
  subscriptions[topic] = stompClient.subscribe(topic, (message) => {
    try {
      const data = JSON.parse(message.body)
      callback(data)
    } catch (error) {
      console.error('解析WebSocket消息失败:', error)
    }
  })
}

export const unsubscribeFromTopic = (topic) => {
  if (subscriptions[topic]) {
    subscriptions[topic].unsubscribe()
    delete subscriptions[topic]
  }
}

export const sendMessage = (destination, message) => {
  if (!stompClient) {
    console.error('WebSocket未连接')
    return
  }
  
  stompClient.send(destination, {}, JSON.stringify(message))
}